<template>
    <div class="container-fluid">
        <div class="panel panel-info">
            <vxe-toolbar class="panel-heading">
                <template #buttons>
                    <div class="row">
                        <div class="col-1">
                        </div>
                        <div class="col-10" style="text-align: center;">
                            <label>个人信息修改</label>
                        </div>
                    </div>
                </template>
            </vxe-toolbar>
            <div class="panel-body">
                <vxe-form ref="xForm" :data="user" :rules="userRules" span="24" title-align="right" title-width="100"
                          title-asterisk>
                    <vxe-form-item title="用户名" field="name">
                        <template #default="params">
                            <vxe-input class="input" v-model="user.name" placeholder="请输入用户名" prefix-icon="fa fa-user"
                                       @input="$refs.xForm.updateStatus(params)" readonly></vxe-input>
                        </template>
                    </vxe-form-item>
                    <vxe-form-item title="昵称" field="nick">
                        <template #default="params">
                            <vxe-input class="input" v-model="user.nick" placeholder="请输入昵称" prefix-icon="fa fa-user-o"
                                       clearable
                                       @input="$refs.xForm.updateStatus(params)">
                            </vxe-input>
                        </template>
                    </vxe-form-item>
                    <vxe-form-item title="头像" field="avatar">
                        <template #default="params">
                            <el-upload
                                class="avatar-uploader"
                                action="http://localhost:9090/upload/minio/upload"
                                :headers="headers"
                                :show-file-list="false"
                                :on-success="handleAvatarSuccess"
                                :before-upload="beforeAvatarUpload">
                                <img v-if="user.avatar" :src="user.avatar" class="avatar" alt="">
                                <i v-else class="el-icon-plus avatar-uploader-icon"></i>
                            </el-upload>
                        </template>
                    </vxe-form-item>
                    <vxe-form-item title="邮箱" field="email">
                        <template #default="params">
                            <vxe-input class="input" v-model="user.email" placeholder="请输入电子邮箱"
                                       prefix-icon="fa fa-envelope" clearable
                                       @input="$refs.xForm.updateStatus(params)" readonly></vxe-input>
                        </template>
                    </vxe-form-item>
                    <vxe-form-item title="性别" field="gender">
                        <template #default="params">
                            <vxe-select class="input" v-model="user.gender" placeholder="请选择性别" clearable
                                        prefix-icon="fa fa-transgender"
                                        @change="$refs.xForm.updateStatus(params);">
                                <vxe-option v-for="g in genders" :value="g.value" :key="g.value"
                                            :label="g.name"></vxe-option>
                            </vxe-select>
                        </template>
                    </vxe-form-item>
                    <vxe-form-item title="生日" field="birthday">
                        <template #default="params">
                            <vxe-input class="input" type="datetime" v-model="user.birthday"
                                       prefix-icon="fa-birthday-cake fa"
                                       placeholder="请选择出生日期" clearable
                                       @input="$refs.xForm.updateStatus(params)"></vxe-input>
                        </template>
                    </vxe-form-item>
                    <vxe-form-item title="地址" span="24" field="address">
                        <template #default="params">
                            <vxe-textarea :autisize="{minRows:2,maxRows:10}" v-model="user.address" placeholder="请输入地址"
                                          maxlength="100" show-word-count clearable
                                          @input="$refs.xForm.updateStatus(params)"></vxe-textarea>
                        </template>
                    </vxe-form-item>
                    <vxe-form-item title="主角色" field="roleId">
                        <template #default="params">
                            <vxe-select v-model="user.roleId" @change="$refs.xForm.updateStatus(params)"
                                        prefix-icon="fa fa-users" disabled>
                                <vxe-option v-for="g in roles" :value="g.id" :key="g.id" :label="g.name"></vxe-option>
                            </vxe-select>
                        </template>
                    </vxe-form-item>
                    <vxe-form-item title="密码" field="password">
                        <template #default="params">
                            <vxe-input class="input" type="password" v-model="user.password" prefix-icon="fa fa-key"
                                       placeholder="请输入密码,不填写表明不修改密码" clearable
                                       @input="$refs.xForm.updateStatus(params)"></vxe-input>
                        </template>
                    </vxe-form-item>
                    <vxe-form-item title="确认密码" field="password1">
                        <template #default="params">
                            <vxe-input class="input" type="password" v-model="user.password1" prefix-icon="fa fa-key"
                                       placeholder="请确认密码,不填写表明不修改密码" clearable
                                       @input="$refs.xForm.updateStatus(params)"></vxe-input>
                        </template>
                    </vxe-form-item>
                </vxe-form>
            </div>
            <div class="panel-footer" style="text-align: center;">
                <vxe-button type="text" status="info" icon="fa fa-remove" @click="close()" content="取消"
                            :loading="isLoading">
                </vxe-button>
                <vxe-button type="text" status="success" icon="fa fa-save" @click="submit()" :content="btnSubmitName"
                            :loading="isLoading">
                </vxe-button>
            </div>
        </div>
    </div>
</template>
<script>
export default {
    name: 'SysUserEdit',
    data () {
        let that = this
        return {
            user: {
                id: null
            },
            genders: [],
            roles: [],
            isLoading: false,
            btnSubmitName: '保存',
            oldEmail: '',
            userRules: {
                name: [{
                    required: true,
                    message: '用户名必填'
                }, {
                    min: 3,
                    max: 10,
                    message: '用户名在三到十个字符之间'
                }, {
                    validator (obj) {
                        if (obj.data.name.length >= 3) {
                            // 后台校验用户名是否存在
                            that.$request.get(that.$apiSys.userExistUrl, {
                                name: obj.data.name,
                                id: obj.data.id
                            }).then(res => {
                                if (!res.valid) {
                                    that.$XModal.message({
                                        content: obj.data.name + '用户名已经存在，请使用其他用户名',
                                        status: 'error'
                                    })
                                    that.user.name = ''
                                }
                            })
                        }
                    }
                }],
                nick: [{
                    required: true,
                    message: '昵称必填'
                }, {
                    min: 1,
                    max: 10,
                    message: '昵称在一个到十个字符之间'
                }],
                email: [{
                    required: true,
                    message: '邮箱必填'
                }, {
                    validator (obj) {
                        if (!/^\w+((-\w+)|(\.\w+))*\@[A-Za-z0-9]+((\.|-)[A-Za-z0-9]+)*\.[A-Za-z0-9]+$/.test(obj.data.email)) {
                            return Error('请输入正确的邮箱地址')
                        }
                    }
                }, {
                    validator (obj) {
                        if (/^\w+((-\w+)|(\.\w+))*\@[A-Za-z0-9]+((\.|-)[A-Za-z0-9]+)*\.[A-Za-z0-9]+$/.test(obj.data.email)) {
                            that.$request.get(that.$apiSys.emailExistUrl, {
                                email: obj.data.email,
                                id: obj.data.id
                            }).then(res => {
                                if (!res.valid) {
                                    that.$XModal.message({
                                        content: obj.data.email + '已经被使用，请使用其他邮箱',
                                        status: 'error'
                                    })
                                    that.user.email = that.oldEmail
                                }
                            })
                        }
                    }
                }],
                gender: [{
                    required: true,
                    message: '请选择性别'
                }],
                birthday: [{
                    required: true,
                    message: '请选择出生日期'
                }],
                address: [{
                    required: true,
                    message: '请输入地址'
                }, {
                    min: 3,
                    max: 100,
                    message: '请输入三到一百个字符之间的地址'
                }],
                roleId: [{
                    required: true,
                    message: '请选择主角色'
                }],
                password: [{
                    min: 6,
                    max: 10,
                    message: '请输入6到10位密码'
                }],
                password1: [{
                    min: 6,
                    max: 10,
                    message: '请输入6到10位密码'
                }, {
                    validator (obj) {
                        console.log(obj.data.password)
                        console.log(obj.data.password1)
                        if (obj.data.password !== obj.data.password1) {
                            return new Error('两次输入的密码不一致')
                        }
                    }
                }]
            },
            headers: {
                token: $.cookie('token') || ''
            }
        }
    },
    created () {
        this.user.id = this.$route.params.id
        this.loadGendersAandRoles()
    },
    mounted () {
    },
    methods: {
        beforeAvatarUpload (file) {
            const isJPG = file.type === 'image/jpeg'
            const isLt2M = file.size / 1024 / 1024 < 2

            if (!isJPG) {
                this.$message.error('上传头像图片只能是 JPG 格式!')
            }
            if (!isLt2M) {
                this.$message.error('上传头像图片大小不能超过 2MB!')
            }
            return isJPG && isLt2M
        },
        handleAvatarSuccess (res, file) {
            console.log(file)
            if (file.status === 'success') {
                if (res.status) {
                    this.user.avatar = res.filePath
                } else {
                    this.$message.error('上传失败：' + res.msg)
                }
            } else {
                this.$message.error('上传失败，请重试')
            }
        },
        loadGendersAandRoles () {
            this.$request.get(this.$apiSys.userGendersUrl).then(data => {
                if (Array.isArray(data)) {
                    this.genders = data
                }
                this.$request.get(this.$apiSys.userRolesUrl).then(data => {
                    if (Array.isArray(data)) {
                        this.roles = data
                    }
                    this.loadData()
                })
            })
        },
        loadData () {
            this.$request.get(this.$apiSys.getUserUrl, {
                id: this.user.id
            }, true).then(user => {
                user.birthday = user.birthday != null ? user.birthday.replace('T', ' ') : user.birthday
                user.createTime = null
                user.updateTime = null
                user.deleteTime = null
                user.password = ''
                user.password1 = ''
                user.roleId = user.roleId + ''
                this.oldEmail = user.email
                this.user = user
            })
        },
        submit () {
            // 校验表单
            this.$refs.xForm.validate(result => {
                if (result !== undefined) {
                    this.$XModal.alert({
                        content: '请检查表单项是否填写正确',
                        status: 'error'
                    })
                    return false
                }
                this.isLoading = true
                this.btnSubmitName = '正在保存，请稍后...'
                this.$request.post(this.$apiSys.userEditUrl, this.user).then(res => {
                    if (res.status) {
                        this.$XModal.message({
                            content: '保存成功',
                            status: 'success'
                        })
                        xadmin.close()
                    } else {
                        // this.$XModal.message({
                        //   content: res.msg,
                        //   status: 'error'
                        // })
                        this.isLoading = false
                        this.btnSubmitName = '保存'
                    }
                }, err => {
                    this.isLoading = false
                    this.btnSubmitName = '保存'
                })
            })
        },
        close () {
            xadmin.close()
        }
    }
}
</script>
<style>

.avatar-uploader .el-upload {
    border: 1px dashed #d9d9d9;
    border-radius: 6px;
    cursor: pointer;
    position: relative;
    overflow: hidden;
}

.avatar-uploader .el-upload:hover {
    border-color: #409EFF;
}

.avatar-uploader-icon {
    font-size: 28px;
    color: #8c939d;
    width: 178px;
    height: 178px;
    line-height: 178px;
    text-align: center;
}

.avatar {
    width: 178px;
    height: 178px;
    display: block;
}

.el-upload__input {
    display: none !important;
}
</style>
